package com.pituruh.tjroute;

import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.pituruh.utils.FindRouteRecord;
import com.pituruh.utils.FindRouteSitesList;
import com.pituruh.utils.FindRouteXMLHandler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.TableRow.LayoutParams;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class FindRouteResult extends Activity implements Runnable {
	/** Create Object For SiteList Class */
	FindRouteRecord findRoute;
	/*private ProgressDialog pd;*/
	FindRouteSitesList sitesList = null;
	ProgressBar pb;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.find_route_result);

		Resources res = getResources();
		int colors[] = { res.getColor(R.color.actionbar_color_1),
				res.getColor(R.color.actionbar_color_2) };
		GradientDrawable grad = new GradientDrawable(Orientation.TOP_BOTTOM,
				colors);
		LinearLayout layout = (LinearLayout) findViewById(R.id.buttonlayout);
		layout.setBackgroundDrawable(grad);

		TextView title_bar = (TextView) findViewById(R.id.title_bar);
		title_bar.setText(R.string.pencarian_rute);

        ImageButton btnShare = (ImageButton) findViewById(R.id.btn_share);
        btnShare.setVisibility(View.VISIBLE);
        ImageView imgSeparator = (ImageView) findViewById(R.id.title_separator);
        imgSeparator.setVisibility(View.VISIBLE);
        
		/****progress dialog***/
/*		pd = ProgressDialog.show(this, getString(R.string.working), getString(R.string.loading_data_from_server), true,
				false);
*/		pb = (ProgressBar) findViewById(R.id.title_progress);
		pb.setVisibility(View.VISIBLE);

		Thread thread = new Thread(this);
		thread.start();

		/****end of progress dialog***/
		
	}

	public void run(){
		try {
			/** Handling XML */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();

			/** Send URL to parse XML Tags */
			URL sourceUrl = new URL(
					"http://transjogja.only.web.id/app/xml/findroute.xml");


			/** Create handler to handle XML Tags ( extends DefaultHandler ) */
			FindRouteXMLHandler myXMLHandler = new FindRouteXMLHandler();
			xr.setContentHandler(myXMLHandler);
			xr.parse(new InputSource(sourceUrl.openStream()));
			sitesList = FindRouteXMLHandler.sitesList;
			/** Get result from MyXMLHandler SitlesList Object */
		} catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}


		
		handler.sendEmptyMessage(0);

	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			/*pd.dismiss();*/
			pb.setVisibility(View.GONE);
			
			if (sitesList == null) {
				Toast.makeText(getApplicationContext(), R.string.failed_loading, Toast.LENGTH_SHORT)
				.show();
				finish();
			}
			else {
				generateTable();
			}
		}
	};

	public void generateTable(){
//		super.onStart();


		/** Get result from MyXMLHandler SitlesList Object */

		TextView startShelter = (TextView) findViewById(R.id.shelter_awal);
		TextView stopShelter = (TextView) findViewById(R.id.shelter_tujuan);
		TextView method = (TextView) findViewById(R.id.metode);
		TextView dateTime = (TextView) findViewById(R.id.tanggal_cari);
		
		startShelter.setText(sitesList.getStartShelter());
		stopShelter.setText(sitesList.getStopShelter());
		method.setText(sitesList.getFindMethod().toString());
		dateTime.setText(sitesList.getDateSearch());
		
        TableLayout tl = (TableLayout) findViewById(R.id.TableLayoutList);

        Integer current = 0;
        for (int i = 0; i < sitesList.getRoutes().getName().size(); i++) {
	           // Create a TableRow and give it an ID
            TableRow tr = new TableRow(this);
            tr.setId(100+current);
            LayoutParams tr_lp = new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT,1);
            tr_lp.setMargins(10,0,0,0);
            tr.setLayoutParams(tr_lp);   

            // Create a TextView to house the name of the province
            TextView labelName = new TextView(this);
            labelName.setId(200+current);
            labelName.setText(sitesList.getRoutes().getName().get(i));
            labelName.setTextColor(Color.BLACK);
            labelName.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT,1));
            tr.addView(labelName);

            String distance = sitesList.getRoutes().getDistance().get(i) + " km (" +
            			sitesList.getRoutes().getDuration().get(i) + " menit)";
            TextView labelKM = new TextView(this);
            labelKM.setId(current);
            labelKM.setText(distance);
            labelKM.setGravity(Gravity.RIGHT);
            labelKM.setTextColor(Color.BLACK);
            LayoutParams labelKM_layout = new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT,1);
            labelKM.setLayoutParams(labelKM_layout);
            labelKM_layout.span = 2;
            tr.addView(labelKM);
            // Add the TableRow to the TableLayout
            tl.addView(tr, new TableLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT,1));		
            
            
	           // Create a TableRow and give it an ID
            TableRow tr1 = new TableRow(this);
            tr1.setId(100+current);
            tr1.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT,1));   
            tr1.setLayoutParams(tr_lp);   
            
            
            // Create a TextView to house the name of the province
            TextView labelJalur = new TextView(this);
            labelJalur.setId(200+current);
            labelJalur.setText(sitesList.getRoutes().getPath().get(i));
            labelJalur.setTextColor(Color.BLACK);
            labelJalur.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT,1));
            tr1.addView(labelJalur);

            TextView labelTime = new TextView(this);
            labelTime.setId(300+current);
            labelTime.setText(R.string.berangkat);
            labelTime.setTextColor(Color.BLACK);
            labelTime.setGravity(Gravity.RIGHT);
            labelTime.setLayoutParams(new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT,1));
            tr1.addView(labelTime);
            
            TextView theTime = new TextView(this);
            theTime.setId(400+current);
            theTime.setText(sitesList.getRoutes().getTime().get(i).toString());
            theTime.setTextColor(Color.BLACK);
            theTime.setGravity(Gravity.RIGHT);
            LayoutParams lpx = new LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT,1);
            lpx.setMargins(10,0,0,0);
            theTime.setLayoutParams(lpx);
            tr1.addView(theTime);
            // Add the TableRow to the TableLayout
            tl.addView(tr1, new TableLayout.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.WRAP_CONTENT,1));	
            
            current++;
		}
	}
	
	public void onHomeClick(View v) {
		startActivity(new Intent(FindRouteResult.this, TJRoute.class));
	}

	public void onCariClick(View v) {
		// startActivity(new Intent(FindRoute.this, FindRoute.class));
		Toast.makeText(getApplicationContext(), "stub", Toast.LENGTH_SHORT)
				.show();
	}
	
	public void onMapClick(View v) {
		startActivity(new Intent(FindRouteResult.this, RouteResultMap.class));
/*		Toast.makeText(getApplicationContext(), "stub", Toast.LENGTH_SHORT)
				.show();
*/	}
}
